package com.maxafa.cropimage;


import java.io.InputStream;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MainSurfaceView extends SurfaceView  implements SurfaceHolder.Callback, Runnable{

	private boolean m_is_running;
	private SurfaceHolder m_surfaceholder;
	private static int s_screen_width, s_screen_height;
	private Paint m_paint;
	private Thread m_mainthread;
	private Canvas m_lockcanvas;
	private float[] m_touch_x, m_touch_y;
	private int m_pointer_count;
	//read resource in asset folder
	private Bitmap m_bitmap_background, m_bitmap_crop;
	private AssetManager m_assetmanager;
	private InputStream m_inputStream;
	private boolean m_cropped;
	
	
	public MainSurfaceView(Context context) {
		super(context);
		m_surfaceholder = getHolder();
		m_surfaceholder.addCallback(this);		
		setFocusable(true);
		s_screen_width = context.getResources().getDisplayMetrics().widthPixels;
		s_screen_height = context.getResources().getDisplayMetrics().heightPixels;
		m_assetmanager = context.getAssets();
	}

	private void Initialize(){
		m_paint = new Paint();		
		try{
			m_inputStream = m_assetmanager.open("images/backgrounds/background.jpg");
			m_bitmap_background = BitmapFactory.decodeStream(m_inputStream);
			m_inputStream.close();
		}catch(Exception e){
			m_inputStream = null;
			m_bitmap_background = null;
		}				
		m_touch_x = new float[2];
		m_touch_y = new float[2];
		m_mainthread = new Thread(this);
		m_mainthread.start();
		m_is_running = true;
		
		
	}
	
	public void GamePause(){
		
	}
	
	public void GameResume(){
		
	}
	
	public void GameExit(){
		
	}
	
	private void GameUpdate(){
		
	}
	
	private void GameDraw(Canvas canvas){
		m_paint.setStrokeWidth(0);
		canvas.drawColor(Color.WHITE);
		if(m_cropped)
			canvas.drawBitmap(m_bitmap_crop, 0, 0, m_paint);
		else
			canvas.drawBitmap(m_bitmap_background, 0, 0, m_paint);
		//draw debug touch rect		
		m_paint.setStrokeWidth(3);
		m_paint.setStyle(Paint.Style.STROKE);
		canvas.drawRect(m_touch_x[0], m_touch_y[0], m_touch_x[1], m_touch_y[1], m_paint);
		
	}

	@Override
	public void run() {
		while(m_is_running){
			try{
				// Thread.sleep(20);
			}catch(Exception e){}
			GameUpdate();
			m_lockcanvas = m_surfaceholder.lockCanvas(null);
			synchronized (m_surfaceholder) {
				if(m_lockcanvas != null){
					GameDraw(m_lockcanvas);
					m_surfaceholder.unlockCanvasAndPost(m_lockcanvas);
				}
			}
		}		
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent e){
		super.onTouchEvent(e);
		m_pointer_count = e.getPointerCount();
		if(e.getActionMasked() == MotionEvent.ACTION_UP || e.getActionMasked() == MotionEvent.ACTION_POINTER_UP){			
			if(m_pointer_count == 1){
				m_pointer_count = 0;				
			}
		}
		if(e.getActionMasked() == MotionEvent.ACTION_DOWN || e.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN){
			if(m_pointer_count > 1){
				m_touch_x[0] = e.getX(0);
				m_touch_y[0] = e.getY(0);
				m_touch_x[1] = e.getX(1);
				m_touch_y[1] = e.getY(1);
			}
		}
		if(e.getActionMasked() == MotionEvent.ACTION_MOVE){
			if(m_pointer_count > 1){
				m_touch_x[0] = e.getX(0);
				m_touch_y[0] = e.getY(0);
				m_touch_x[1] = e.getX(1);
				m_touch_y[1] = e.getY(1);
			}
		}
		return true;
	}
	
	public boolean IsCropped(){
		return m_cropped;
	}
	
	public void ResetCrop(){
		m_cropped = false;
	}
	
	public void DoCrop(){
		if(!m_cropped){
			int left = (int)(m_touch_x[0]<m_touch_x[1]?m_touch_x[0]:m_touch_x[1]);
			int top = (int)(m_touch_y[0]<m_touch_y[1]?m_touch_y[0]:m_touch_y[1]);
			int width = (int)Math.abs(m_touch_x[1] - m_touch_x[0]);
			int height = (int)Math.abs(m_touch_y[1] - m_touch_y[0]);
			m_bitmap_crop = Bitmap.createBitmap(m_bitmap_background, left, top, width, height);
			m_cropped = true;
			m_touch_x[0] = -1;
			m_touch_y[0] = -1;
			m_touch_x[1] = -1;
			m_touch_y[1] = -1;
		}		
	}

	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void surfaceCreated(SurfaceHolder arg0) {
		Initialize();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		boolean retry = true;
		m_is_running = false;
        do {
            try {
                m_mainthread.join();
                retry = false;
            } catch (InterruptedException e) {
				e.printStackTrace();
                // we will try it again and again...
            }
        }while(retry);		
	}
}
